package cn.butcher21.view;

import cn.butcher21.Main;
import cn.butcher21.dao.UserDao;
import cn.butcher21.utils.BuildScene;
import cn.butcher21.window.CashWindow;
import cn.butcher21.window.CusPayWindow;
import cn.butcher21.window.MainWindow;
import cn.butcher21.window.WeScanWindow;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

public class LoginController {

    @FXML
    private Button login;

    @FXML
    private Button reset;

    @FXML
    private TextField username;

    @FXML
    private PasswordField password;

    @FXML
    private Label tips;

    @FXML
    private ImageView img;


    @FXML
    private void initialize() throws Exception {
        Context.rootController.put(this.getClass().getSimpleName(), this);
        username.setText("admin");
        password.setText("123");
        img.setImage(new Image(new File("src/main/resources/loginbg.jpg").toURI().toString()));
    }


    @FXML
    void login(ActionEvent event) {
        UserDao userDao = new UserDao();
        try {
            String password = DigestUtils.md5Hex(this.password.getText());
            boolean checkUser = userDao.checkUser(username.getText(), password);
            if (checkUser) {
                tips.setText("口令正确，正在跳转，请稍等...");
                // 关闭登录窗口
                BuildScene.stages.get("loginStage").close();

                // 显示主窗口
                new MainWindow();
                BuildScene.stages.get("mainStage").show();
            } else {
                tips.setText("登录失败了，瞧你这记性！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @FXML
    void resetMsg(ActionEvent event) {
        username.setText("");
        password.setText("");
        tips.setText("");
    }

    public TextField getUsername() {
        return username;
    }
}
